# -*- coding: utf-8 -*-

import base64
import os
import re

from mailarchive.api import EmailException, IEmailHandler
from trac.attachment import Attachment
from trac.core import *
from trac.mimeview.api import KNOWN_MIME_TYPES
from trac.config import Option
from trac.perm import PermissionSystem
from trac.ticket import Ticket
from trac.ticket.notification import TicketNotifyEmail
from StringIO import StringIO

class MailFilter(Component):
    """create a ticket from an email"""

    implements(IEmailHandler)

    ### methods for IEmailHandler

    def match(self, message):
        return True

    def invoke(self, status, message, warnings):
        """make a new ticket on receiving email"""
        print "MailFilter.invoke, %s" % (status)
        
        if status == IEmailHandler.UPDATE:
            return
        
        section = self.env.config['mailfilter']
        
        name_list = []
        for (name, value) in section.options():
            name_list.append(name.split('.')[0])
            
        name_list.sort()
        
        rules = []
        for name in set(name_list):
            data = {}
            data['condition'] = section.get(name + '.condition')
            data['action'] = section.get(name + '.action')
            rules.append(data)
            
        for rule in rules:
            stop = self.execute_rule(rule, message)
            if stop:
                break
            

    def execute_rule(self, rule, message):
        con = rule['condition'].split('|')
        
        target = ''
        
        if con[0] == 'subject':
            target = message['subject'] 
        elif con[0] == 'body':
            target = message['body'] 
        
        if re.match(con[1], target):
           self.execute_action(rule['action'], message)
           return True
        
        return False
        
    def execute_action(self, action, message):
        try:
            if action == 'new_ticket':
                db = self.env.get_db_cnx()
                cursor = db.cursor()
                cursor.execute('SELECT id FROM ticket WHERE summary=%s', (message['subject'],))
                row = cursor.fetchone()
                if row is not None:
                    print 'already exsit ticket'
                    return
                
                print "new-ticket! %s" % (message['messageid'])
                ticket = Ticket(self.env)
                data = {}
                data['reporter'] = message['fromaddr'] 
                data['summary'] = message['subject'] 
                data['description'] = message['body']
                data['mail_id'] = str(message['id'])
                ticket.populate(data)
                ticket.insert()

        except Exception, e:
            print e

    def order(self):
        return None

    

